package http

import (
	"driverTest/device"
	"log"
	"net"
	"time"
)

func SocketStart() {
	ip := "0.0.0.0:"
	port := "9999"
	address := ip + port
	listen, err := net.Listen("tcp", address)
	if listen == nil {
		log.Println("listen == nil")
		return
	}
	if err != nil {
		log.Printf("监听失败:%s,%s\n", address, err.Error())
		listen.Close()
		return
	}

	log.Printf("塔吊监听 【%s】成功\n", port)
	go AcceptConn(listen)
}

func AcceptConn(l net.Listener) {
	for {
		conn, err := l.Accept()
		if err != nil {
			log.Printf("塔吊监听建立连接错误:%s\n", err.Error())
			l.Close()
			continue
		}
		log.Printf("创建连接 %v\n", conn.RemoteAddr)
		go AcceptHandler(conn)
	}
}

func AcceptHandler(conn net.Conn) {
	defer func() {
		conn.Close()
		log.Printf("塔吊监听处理发生错误\n")
		//设置设备状态
	}()
	readCh := make(chan []byte, 5)
	writeCh := make(chan []byte, 3)
	statusCh := make(chan bool, 1)
	timeout := time.NewTimer(5 * time.Second)
	go func() {
		time.Sleep(time.Second * 5)
		writeCh <- device.CreatData()
	}()
	go socketWrite(conn, writeCh)
	go socketReadTask(conn)
	for {
		var dat []byte
		var state bool
		timeout.Reset(5 * time.Second)
		select {
		case dat = <-readCh:
			log.Printf("%x", dat)
			break
		case state = <-statusCh:
			if false == state {
				return
			}
		}
	}
}

func socketWrite(conn net.Conn, writeCh chan []byte) {
	defer func() {
		conn.Close()
	}()
	for {
		select {
		case data := <-writeCh:
			n, err := conn.Write(data)
			if err != nil {
				log.Printf("error %+v", err)
			}
			log.Printf("data send %d byte% x success\n", n, data)
			// log.Printf("recv: %+v", buf[:n])
		}
	}
}

func socketReadTask(conn net.Conn) {
	if conn == nil {
		return
	}
	var tempBuff []byte
	buff := make([]byte, 1024)

	for {
		n, err := conn.Read(buff)
		if err != nil {
			log.Printf("读数据错误：%s\n", err.Error())
			return
		}
		tempBuff = append(tempBuff, buff[:n]...)
		//log.Printf("当前数据：%x \n", tempBuff)
		tempBuff = Unpack(tempBuff)
	}

}

func Unpack(src []byte) []byte {
	return []byte{}
}

func CheckSum() {

}
